package com.yupi.ojsystem.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.ojsystem.common.ErrorCode;
import com.yupi.ojsystem.exception.BusinessException;
import com.yupi.ojsystem.exception.ThrowUtils;
import com.yupi.ojsystem.judge.JudgeManager;
import com.yupi.ojsystem.judge.codesandbox.CodeSandbox;
import com.yupi.ojsystem.judge.codesandbox.CodeSandboxFactory;
import com.yupi.ojsystem.judge.codesandbox.CodeSandboxProxy;
import com.yupi.ojsystem.judge.codesandbox.JudgeService;
import com.yupi.ojsystem.judge.codesandbox.model.ExecuteCodeRequest;
import com.yupi.ojsystem.judge.codesandbox.model.ExecuteCodeResponse;
import com.yupi.ojsystem.judge.strategy.JudgeContext;
import com.yupi.ojsystem.model.dto.question.JudgeCase;
import com.yupi.ojsystem.judge.codesandbox.model.JudgeInfo;
import com.yupi.ojsystem.model.dto.question.JudgeConfig;
import com.yupi.ojsystem.model.entity.Question;
import com.yupi.ojsystem.model.entity.QuestionSubmit;
import com.yupi.ojsystem.model.enums.JudgeInfoMessageEnum;
import com.yupi.ojsystem.model.enums.QuestionSubmitStatusEnum;
import com.yupi.ojsystem.service.IQuestionService;
import com.yupi.ojsystem.service.IQuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServicelmpl implements JudgeService {
    @Resource
    IQuestionSubmitService questionSubmitService;
    @Resource
    IQuestionService questionService;

    @Value("${codesandbox.type}")
    String type;
    @Resource
    JudgeManager judgeManager;
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //传入提交的id，获取对应的题目信息
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        //判断提交信息是否存在
        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        //判断题目是否存在
        Question question = questionService.getById(questionSubmit.getQuestionId());
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        //如果不为等待状态，抛出异常
        if(questionSubmit.getStatus() != QuestionSubmitStatusEnum.WAITING.getValue()){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中");
        }
        //更改题目状态为"判题中"，防止重复执行
        QuestionSubmit updateQuestionSubmit = new QuestionSubmit();
        updateQuestionSubmit.setId(questionSubmitId);
        updateQuestionSubmit.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(updateQuestionSubmit);
        ThrowUtils.throwIf(!update,ErrorCode.SYSTEM_ERROR,"题目状态更新失败");
        //调用代码沙箱，获取执行结果
        CodeSandbox codeSandbox= CodeSandboxFactory.newInstance(type);
        codeSandbox=new CodeSandboxProxy(codeSandbox);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        //获取输入用例
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
//        List<String> inputList = judgeCaseList.stream()
//                .map(JudgeCase::getInput)
//                .collect(Collectors.toList());
        // 将每个 input 字符串按逗号分割，并展平为一个集合
        List<String> inputList = judgeCaseList.stream()
                .map(JudgeCase::getInput) // 获取每个 JudgeCase 的 input 字段
                .flatMap(input -> StrUtil.splitTrim(input, ',').stream()) // 按逗号分割并展平
                .collect(Collectors.toList()); // 收集结果为一个列表
        //构造执行代码请求
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .language(language)
                .code(code)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        JudgeInfoMessageEnum judgeInfoMessageEnum=JudgeInfoMessageEnum.WAITING;
        List<String> ouputList = executeCodeResponse.getOuputList();
        //构造judgeContext
        JudgeContext judgeContext=new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(ouputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        //更新数据库
        updateQuestionSubmit = new QuestionSubmit();
        updateQuestionSubmit.setId(questionSubmitId);
        updateQuestionSubmit.setStatus(QuestionSubmitStatusEnum.SUCCESS.getValue());
        if(executeCodeResponse.getStatus().equals(3)){
            updateQuestionSubmit.setStatus(QuestionSubmitStatusEnum.FAILED.getValue());
        }
        if(judgeInfo.getMessage().equals(JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED.getValue())){
            updateQuestionSubmit.setStatus(QuestionSubmitStatusEnum.FAILED.getValue());
        }
        JudgeConfig judgeConfig = JSONUtil.toBean(question.getJudgeConfig(), JudgeConfig.class);
        if(judgeConfig.getTimeLimit()< judgeInfo.getTime()){
            updateQuestionSubmit.setStatus(QuestionSubmitStatusEnum.FAILED.getValue());
            judgeInfo.setMessage(JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED.getValue());
        }
//        if(executeCodeResponse.getJudgeInfo().getMemory())
        updateQuestionSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(updateQuestionSubmit);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);
        return questionSubmitResult;
    }
}
